package com.task.core.service.impl;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.stream.Collectors;
import javax.annotation.Resource;

import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;

import com.task.common.exception.ServiceException;
import com.task.common.utils.SecurityUtils;
import com.task.common.utils.StringUtils;
import com.task.core.domain.SystemSettingInfo;
import com.task.core.dto.request.SysSettingModifyRequestDTO;
import com.task.core.dto.request.SysSettingRequestDTO;
import com.task.core.dto.response.SysSettingResponseDTO;
import com.task.core.mapper.SysSettingMapper;
import com.task.core.service.SysSettingService;

/**
 * @author 迪迦.
 * @date 2025/2/10 11:22
 */
@Service
public class SysSettingServiceImpl implements SysSettingService {

  @Resource
  private SysSettingMapper sysSettingMapper;

  @Override
  public List<SysSettingResponseDTO> getAllSetting(SysSettingRequestDTO request) {
    List<SysSettingResponseDTO> response = new ArrayList<>();
    List<SystemSettingInfo> infos = sysSettingMapper.getAllSetting(request);
    if (CollectionUtils.isEmpty(infos)) {
      return response;
    }
    Map<String, List<SystemSettingInfo>> collect = infos.stream().collect(Collectors.groupingBy(SystemSettingInfo::getType));
    for (Entry<String, List<SystemSettingInfo>> entry : collect.entrySet()) {
      response.add(new SysSettingResponseDTO(entry.getKey(), entry.getValue().get(0).getTypeDisplayTitle(), entry.getValue()));
    }
    return response;
  }

  @Override
  public void modifySettingByCode(SysSettingModifyRequestDTO request) {
    request.setOperationBy(SecurityUtils.getLoginUser().getUserId());
    Integer integer = sysSettingMapper.modifySettingByCode(request);
    if(integer == 0) {
      throw new ServiceException("code不存在");
    }
  }

  @Override
  public List<SystemSettingInfo> getSettingByType(SysSettingRequestDTO request) {
    if(StringUtils.isEmpty(request.getType())) {
      throw new ServiceException("类型不能为空");
    }
    return sysSettingMapper.getSettingByType(request);
  }

  @Override
  public SystemSettingInfo getSettingByTypeAndKey(SysSettingRequestDTO request) {
    if(StringUtils.isEmpty(request.getType())) {
      throw new ServiceException("类型不能为空");
    }
    if(StringUtils.isEmpty(request.getField())) {
      throw new ServiceException("键不能为空");
    }
    SystemSettingInfo settingByTypeAndKey = sysSettingMapper.getSettingByTypeAndKey(request);
    if (ObjectUtils.isEmpty(settingByTypeAndKey)) {
      throw new ServiceException("系统配置项空");
    }
    return settingByTypeAndKey;
  }
}
